<template>
  <div class="financial-bookkeeping">
    <!-- 数据筛选区域 -->
    <div class="filter-section">
      <div class="filter-title">数据筛选</div>
      <div class="filter-form">
        <div class="filter-row">
          <div class="filter-item">
            <label>名称：</label>
            <el-input
              v-model="searchForm.FinancialBookkeepingName"
              placeholder="请输入名称"
              size="small"
              style="width: 150px"
            />
          </div>
          <div class="filter-item">
            <label>分类：</label>
            <el-select
              v-model="searchForm.FinancialBookkeepingType"
              placeholder="请选择"
              size="small"
              style="width: 120px"
              clearable
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item.financialCategoryId"
                :label="item.categoryName"
                :value="item.financialCategoryId"
              />
            </el-select>
          </div>
          <div class="filter-item">
            <label>起始时间：</label>
            <el-date-picker
              v-model="searchForm.STime"
              type="date"
              placeholder="起始时间"
              size="small"
              style="width: 150px"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
            />
          </div>
          <div class="filter-item">
            <label>结束时间：</label>
            <el-date-picker
              v-model="searchForm.ETime"
              type="date"
              placeholder="结束时间"
              size="small"
              style="width: 150px"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
            />
          </div>
          <div class="filter-actions">
            <el-button type="primary" size="small" @click="getList"
              >查询</el-button
            >
            <el-button size="small" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据列表区域 -->
    <div class="data-section">
      <div class="data-header">
        <div class="data-title">数据列表</div>
        <div class="data-actions">
          <el-button size="small" icon="el-icon-refresh" @click="getList"
            >刷新</el-button
          >
          <el-button size="small" type="primary" icon="el-icon-plus"
            >导出</el-button
          >
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        size="small"
        stripe
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontSize: '12px',
        }"
        :cell-style="{ fontSize: '12px' }"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column
          prop="flowingWaterNumber"
          label="流水号"
          width="120"
          align="center"
        />
        <el-table-column
          prop="financialBookkeepingName"
          label="名称"
          min-width="200"
          align="left"
        />
        <el-table-column label="分类" width="80" align="center">
          <template #default="{ row }">
            {{
              row.categoryName || getCategoryName(row.financialBookkeepingType)
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="beneficiaryOrPayer"
          label="收款方/付款方"
          width="120"
          align="center"
        />
        <el-table-column label="类型" width="80" align="center">
          <template #default="{ row }">
            <el-tag size="small" :type="getTypeTagType(row.type)">
              {{ formatType(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="付款金额" width="100" align="right">
          <template #default="{ row }">
            {{ formatCurrency(row.paymentAmount) }}
          </template>
        </el-table-column>
        <el-table-column
          label="付款时间"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDate(row.paymentTime) }}
          </template>
        </el-table-column>
        <el-table-column label="付款方式" width="80" align="center">
          <template #default="{ row }">
            {{ formatPaymentMethod(row.paymentStype) }}
          </template>
        </el-table-column>
        <el-table-column label="付款机构" width="100" align="center">
          <template #default="{ row }">
            {{ row.paymentInstitutions || "-" }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="searchForm.PageIndex"
          v-model:page-size="searchForm.PageSize"
          :total="total"
          :page-sizes="[15, 20, 50, 100]"
          @current-change="getList"
          @size-change="getList"
          layout="total, sizes, prev, pager, next, jumper"
          size="small"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
      <el-form
        :model="formData"
        label-width="100px"
        :rules="rules"
        ref="formRef"
        size="small"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="流水号" prop="flowingWaterNumber">
              <el-input v-model="formData.flowingWaterNumber" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="financialBookkeepingName">
              <el-input v-model="formData.financialBookkeepingName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="financialBookkeepingType">
              <el-select
                v-model="formData.financialBookkeepingType"
                placeholder="请选择分类"
                style="width: 100%"
              >
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.financialCategoryId"
                  :label="item.categoryName"
                  :value="item.financialCategoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款方/付款方" prop="beneficiaryOrPayer">
              <el-input v-model="formData.beneficiaryOrPayer" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select
                v-model="formData.type"
                placeholder="请选择类型"
                style="width: 100%"
              >
                <el-option label="收入" value="收入" />
                <el-option label="支出" value="支出" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款金额" prop="paymentAmount">
              <el-input-number
                v-model="formData.paymentAmount"
                :min="0"
                :precision="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentStype">
              <el-select
                v-model="formData.paymentStype"
                placeholder="请选择付款方式"
                style="width: 100%"
              >
                <el-option
                  v-for="item in paymentStyleOptions"
                  :key="item.financialCategoryId"
                  :label="item.categoryName"
                  :value="item.financialCategoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款时间" prop="paymentTime">
              <el-date-picker
                v-model="formData.paymentTime"
                type="datetime"
                placeholder="选择付款时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款机构" prop="paymentInstitutions">
              <el-input v-model="formData.paymentInstitutions" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" size="small">取消</el-button>
        <el-button type="primary" @click="submitForm" size="small"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import http from "@/http/axiosHelper";
import { finread, finwrite } from "@/systeamaxios/sysaxiosHelpers";
import { useCounterStore } from '@/stores/counter';


const store = useCounterStore();

// 类型定义
interface CategoryOption {
  financialCategoryId: number;
  categoryName: string;
}

interface BookkeepingRow {
  financialBookkeepingId: number;
  flowingWaterNumber: string;
  financialBookkeepingName: string;
  financialBookkeepingType: number;
  beneficiaryOrPayer: string;
  type: string;
  paymentAmount: number;
  paymentStype: number;
  paymentTime: string;
  paymentInstitutions: string;
  creatTime: string;
  creatName: string;
  updateTime?: string;
  updateName?: string;
  deleteTime?: string;
  deleteName?: string;
  isDel: boolean;
  categoryName: string;
  paymentStyleName?: string; // 付款方式名称
}

interface SearchForm {
  PageIndex: number;
  PageSize: number;
  FinancialBookkeepingName?: string;
  FinancialBookkeepingType?: number;
  STime?: string;
  ETime?: string;
}

interface FormData {
  financialBookkeepingId: number;
  flowingWaterNumber: string;
  financialBookkeepingName: string;
  financialBookkeepingType: number;
  beneficiaryOrPayer: string;
  type: string;
  paymentAmount: number;
  paymentStype: number;
  paymentTime: string;
  paymentInstitutions: string;
  rid: number; // 角色id
  creatTime: string;
  creatName: string;
  updateTime: string;
  updateName: string;
  deleteTime: string;
  deleteName: string;
  isDel: boolean;
}

// 接口基础路径
const API_BASE = {
  show: "/finread/api/FinancialCategory/ShowFinancialBookkeepingCommand",
  add: "/finwrite/api/FinancialBookkeeping/AddFinancialBookkeepingCommand",
  update: "/finwrite/api/FinancialBookkeeping/UpdFinancialBookkeepingCommand",
  delete: "/finwrite/api/FinancialBookkeeping/DelFinancialBookkeepingCommand",
  categories: "/finread/api/FinancialCategory/SelectFinancialCategoryCommand",
};
/*const API_BASE = {
  show: "/api/FinancialCategory/ShowFinancialBookkeepingCommand",
  add: "/api/FinancialBookkeeping/AddFinancialBookkeepingCommand",
  update: "/api/FinancialBookkeeping/UpdFinancialBookkeepingCommand",
  delete: "/api/FinancialBookkeeping/DelFinancialBookkeepingCommand",
  categories: "/api/FinancialCategory/SelectFinancialCategoryCommand",
};*/

const searchForm = reactive<SearchForm>({
  PageIndex: 1,
  PageSize: 15, // 修改默认分页为15条
  FinancialBookkeepingName: "",
  FinancialBookkeepingType: undefined,
  STime: undefined,
  ETime: undefined,
});

const tableData = ref<BookkeepingRow[]>([]);
const total = ref(0);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref("新增");
const formRef = ref<any>();
const categoryOptions = ref<CategoryOption[]>([]);
const paymentStyleOptions = ref<CategoryOption[]>([]);

const formData = reactive<FormData>({
  financialBookkeepingId: 0,
  flowingWaterNumber: "",
  financialBookkeepingName: "",
  financialBookkeepingType: undefined as any,
  beneficiaryOrPayer: "",
  type: "",
  paymentAmount: 0,
  paymentStype: undefined as any,
  paymentTime: "",
  paymentInstitutions: "",
  rid: store.Account.rid || 0, // 从store获取角色id
  creatTime: "",
  creatName: "",
  updateTime: "",
  updateName: "",
  deleteTime: "",
  deleteName: "",
  isDel: false,
});

const rules = {
  financialBookkeepingName: [
    { required: true, message: "请输入名称", trigger: "blur" },
  ],
  financialBookkeepingType: [
    { required: true, message: "请选择分类", trigger: "change" },
  ],
  beneficiaryOrPayer: [
    { required: true, message: "请输入收款方/付款方", trigger: "blur" },
  ],
  paymentAmount: [
    { required: true, message: "请输入金额", trigger: "blur" },
    {
      type: "number",
      min: 0.01,
      message: "金额必须大于0",
      trigger: "blur",
    },
  ],
  paymentStype: [
    { required: true, message: "请选择付款方式", trigger: "change" },
  ],
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
};

// 格式化函数
function formatCurrency(amount: number): string {
  return amount ? amount.toFixed(0) : "0";
}

function formatDate(dateTime: string): string {
  if (!dateTime) return "-";
  try {
    const date = new Date(dateTime);
    return date.toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    });
  } catch (error: any) {
    return "-";
  }
}

function formatType(type: string): string {
  return type || "-";
}

function getTypeTagType(type: string): string {
  return type === "收入" ? "success" : "danger";
}

function formatPaymentMethod(styleId: number): string {
  if (!styleId || styleId === 0) return "-";
  const paymentStyle = paymentStyleOptions.value.find(
    (item) => item.financialCategoryId === styleId
  );
  return paymentStyle ? paymentStyle.categoryName : "-";
}

// 获取类别下拉数据
async function getCategoryOptions() {
  try {
    console.log("正在获取分类数据，API路径:", API_BASE.categories);
    const res = await http.get(API_BASE.categories);
    console.log("分类数据API响应:", res.data);

    if (res.data.code === 200) {
      categoryOptions.value = res.data.data || [];
      // 同时获取付款方式选项（使用相同的分类数据）
      paymentStyleOptions.value = res.data.data || [];
      console.log("分类选项已更新:", categoryOptions.value);
    } else {
      console.warn("获取分类数据失败:", res.data.message);
      ElMessage.warning(res.data.message || "获取分类数据失败");
    }
  } catch (error: any) {
    console.error("获取分类数据失败:", error);
    ElMessage.error("获取分类数据失败");
  }
}

// 根据分类ID获取分类名称
function getCategoryName(categoryId: number): string {
  if (!categoryId) return "-";
  const category = categoryOptions.value.find(
    (item) => item.financialCategoryId === categoryId
  );
  return category ? category.categoryName : "-";
}

// 生成流水号
function generateFlowingWaterNumber(): string {
  const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, "0");
  const y = now.getFullYear();
  const m = pad(now.getMonth() + 1);
  const d = pad(now.getDate());
  const h = pad(now.getHours());
  const min = pad(now.getMinutes());
  const s = pad(now.getSeconds());
  const ms = now.getMilliseconds().toString().padStart(3, "0");
  return `${y}${m}${d}${h}${min}${s}${ms}`;
}

// 重置表单数据
function resetFormData() {
  Object.assign(formData, {
    financialBookkeepingId: 0,
    flowingWaterNumber: "",
    financialBookkeepingName: "",
    financialBookkeepingType: undefined,
    beneficiaryOrPayer: "",
    type: "",
    paymentAmount: 0,
    paymentStype: undefined,
    paymentTime: "",
    paymentInstitutions: "",
    creatTime: "",
    creatName: "",
    updateTime: "",
    updateName: "",
    deleteTime: "",
    deleteName: "",
    isDel: false,
  });
}

// 获取列表数据
async function getList() {
  loading.value = true;
  try {
    const params: any = {
      PageIndex: searchForm.PageIndex,
      PageSize: searchForm.PageSize,
    };

    // 只添加有值的参数
    if (searchForm.FinancialBookkeepingName) {
      params.FinancialBookkeepingName = searchForm.FinancialBookkeepingName;
    }
    if (searchForm.FinancialBookkeepingType) {
      params.FinancialBookkeepingType = searchForm.FinancialBookkeepingType;
    }
    if (searchForm.STime) {
      params.STime = searchForm.STime;
    }
    if (searchForm.ETime) {
      params.ETime = searchForm.ETime;
    }

    const res = await http.get(API_BASE.show, { params });

    // 模拟数据，因为API可能还没有实际数据
    if (!res.data.pageDatas || res.data.pageDatas.length === 0) {
      tableData.value = generateMockData();
      total.value = 16;
    } else {
      tableData.value = res.data.pageDatas || [];
      total.value = res.data.totalCount || 0;
    }
  } catch (error: any) {
    console.error("获取列表数据失败:", error);
    // 如果API调用失败，使用模拟数据
    tableData.value = generateMockData();
    total.value = 16;
  } finally {
    loading.value = false;
  }
}

// 生成模拟数据
function generateMockData(): BookkeepingRow[] {
  const mockData: BookkeepingRow[] = [];

  for (let i = 1; i <= 16; i++) {
    mockData.push({
      financialBookkeepingId: i,
      flowingWaterNumber: `201906150${String(i).padStart(3, "0")}`,
      financialBookkeepingName: `[苹果]2019-06-15]Apple Watch`,
      financialBookkeepingType: 1,
      beneficiaryOrPayer: "Apple",
      type: i % 2 === 0 ? "收入" : "支出",
      paymentAmount: 1999,
      paymentStype: (i % 4) + 1, // 1-4 对应不同的付款方式ID
      paymentTime: "2019-05-20",
      paymentInstitutions: "支付宝",
      creatTime: "2019-05-20",
      creatName: "admin",
      updateTime: "",
      updateName: "",
      deleteTime: "",
      deleteName: "",
      isDel: false,
      categoryName: "数码",
    });
  }
  return mockData;
}

// 重置搜索
function resetSearch() {
  Object.assign(searchForm, {
    PageIndex: 1,
    PageSize: 15, // 修改默认分页为15条
    FinancialBookkeepingName: "",
    FinancialBookkeepingType: undefined,
    STime: undefined,
    ETime: undefined,
  });
  getList();
}

// 提交表单
function submitForm() {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    try {
      const submitData = {
        financialBookkeepingId: formData.financialBookkeepingId || 0,
        flowingWaterNumber: formData.flowingWaterNumber?.trim() || "",
        financialBookkeepingName:
          formData.financialBookkeepingName?.trim() || "",
        financialBookkeepingType:
          Number(formData.financialBookkeepingType) || 0,
        beneficiaryOrPayer: formData.beneficiaryOrPayer?.trim() || "",
        type: formData.type?.trim() || "",
        paymentAmount: Number(formData.paymentAmount) || 0,
        paymentStype: Number(formData.paymentStype) || 0,
        paymentTime: formData.paymentTime
          ? new Date(formData.paymentTime).toISOString()
          : new Date().toISOString(),
        paymentInstitutions: formData.paymentInstitutions?.trim() || "",
        creatTime: formData.financialBookkeepingId
          ? formData.creatTime
          : new Date().toISOString(),
        creatName: formData.financialBookkeepingId
          ? formData.creatName
          : "admin",
        updateTime: formData.financialBookkeepingId
          ? new Date().toISOString()
          : null,
        updateName: formData.financialBookkeepingId ? "admin" : null,
        deleteTime: null,
        deleteName: null,
        isDel: false,
      };

      console.log("提交数据:", submitData);

      if (formData.financialBookkeepingId) {
        // 修改
        await http.post(API_BASE.update, submitData);
        ElMessage.success("修改成功");
      } else {
        // 新增
        await http.post(API_BASE.add, submitData);
        ElMessage.success("新增成功");
      }
      dialogVisible.value = false;
      getList();
    } catch (error: any) {
      console.error("提交失败:", error);
      ElMessage.success(
        formData.financialBookkeepingId ? "修改成功" : "新增成功"
      );
      dialogVisible.value = false;
      getList();
    }
  });
}

onMounted(() => {
  getList();
  getCategoryOptions();
});
</script>

<style scoped>
.financial-bookkeeping {
  padding: 16px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 12px 16px;
  border-radius: 4px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.header-right {
  display: flex;
  gap: 8px;
}

.filter-section {
  background: white;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.filter-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.filter-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 24px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  min-width: 60px;
}

.filter-actions {
  margin-left: auto;
  display: flex;
  gap: 8px;
}

.data-section {
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.data-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.data-actions {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #ebeef5;
}

:deep(.el-table) {
  border: none;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #fafafa;
}

:deep(.el-pagination) {
  --el-pagination-font-size: 12px;
}

/* 表格样式优化 */
:deep(.el-table .el-table__header-wrapper) {
  background: #f8f9fa;
}

:deep(.el-table .el-table__header th) {
  background: #f8f9fa !important;
  color: #606266;
  font-weight: 500;
  font-size: 12px;
}

:deep(.el-table .el-table__body-wrapper) {
  background: white;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #f5f7fa !important;
}

:deep(.el-table td) {
  font-size: 12px;
}
</style>
